import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import { getCardType } from '../api';
import type CardTypeItem from '../models/CardTypeItem';
import CardTypeList, { CardTypeQuery } from '../models/CardTypeList';

const useCardType = () => {
  const params = ref<CardTypeQuery>(new CardTypeQuery());

  const state = ref<ListState<CardTypeItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getCardType(params.value);
      const resultData = deserialize(data, CardTypeList);
      state.value.data = resultData.items.sort((a, b) => +a.code - +b.code);
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };
  return {
    params,
    state,
    fetchData,
  };
};

export default useCardType;
